package com.utra.hellshan.upload.NetTool;
/**
 * 类名 NetClient
 * 作用 用于登录注册等用户相关的操作（不包含操作鹰眼实例）
 * 约定：
 *         登录操作：发送 用户#密码#TYPE_LOGIN
 *         注册操作：发送 用户#密码#TYPE_REGISTER
 *         查询用户是否存在： 发送 用户#DEFAULT#TYPE_CHECK
 *         服务器均返回 SUCCESS 或 FAIL
 *         其中 TYPE_LOGIN TYPE_REGISTER TYPE_CHECK DEFAULT SUCCESS FAIL 均为普通字符串 **/
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.utra.hellshan.upload.OtherTools.SystemUtil;

import java.io.*;
import java.net.*;

public class NetClient{

    public static String TYPE_REGISTER = "TYPE_REGISTER";    //注册
    public static String TYPE_LOGIN = "TYPE_LOGIN";   //登录
    private static String TYPE_CHECK = "TYPE_CHECK";  //检查该用户名是否已经注册
    public final static String SUCCESS = "SUCCESS" ;





    private static Socket socket;


    private static String serverEcho;
    private static boolean handlerEnd = false;

    private static Context ctx ;

    static private byte[] addr = {101 , (byte)201 , 66,99} ;    //服务器IP地址

    private static BufferedReader input;      //socket输入流
    private static PrintStream output;          //socket输出流


    static Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            if(bundle.containsKey("echo"))
            {
                NetClient.serverEcho = new String((String)bundle.get("echo"));
            }
            handlerEnd = true;
        }
    };




    public static void Init(Context context , byte[] address)
    {

        addr = address;
        ctx = context;
        handlerEnd = false;

        try {
            socket=new Socket(InetAddress.getByAddress(addr),1888);       ///链接用户登录服务器
        }catch(Exception e)                                                     //后期代码优化应细化异常处理
        {
            Toast.makeText(ctx , "Server connect error \n  Error code : E - N - 1 " , Toast.LENGTH_LONG).show();
            return;
        }
    }


    public static void Init(Context context)    //只能用多线程访问网络
    {
        ctx = context;
/*  暂时跳过服务器验证 - 9.25
                try
                {
                    socket = new Socket(InetAddress.getByAddress(addr),1888);       ///链接用户登录服务器
                    input =  new BufferedReader(new InputStreamReader(socket.getInputStream()));                                      //读取输入
                    output = new PrintStream(socket.getOutputStream());
                    //output = new OutputStreamWriter(socket.getOutputStream());            //输出数据用
                    Toast.makeText(ctx , "Toast test" , Toast.LENGTH_LONG).show();

                }catch(Exception e) //后期代码优化应细化异常处理

                {
                    Toast.makeText(ctx , "Server connect error \n  无法连接服务器" , Toast.LENGTH_LONG).show();
                    Toast.makeText(ctx , e.toString() , Toast.LENGTH_LONG).show();

                }
*/
    }

    private static boolean SendRequest( final String userName_, final String userPassword_, final String requestType_ , final String clientInfo_)
    {




/*
        new Thread(
                new Runnable() {
                    public void run() {
                        Looper.prepare();
                        String temp = new String();
                        char temp_ ;
                        Bundle bundle = new Bundle();
                        Message message = new Message();

                        try {
                            //output.write(requestType_ + "#" + userName_ + "#" + userPassword_ + "#" + clientInfo_); //register#账号#密码
                            //output.flush();
                            output.print(requestType_ + "#" + userName_ + "#" + userPassword_ + "#" + clientInfo_);
                            temp = input.readLine();
                            Toast.makeText(ctx , new String(temp) , Toast.LENGTH_LONG).show();
                            bundle.putString("echo" , new String(temp));
                            message.setData(bundle);
                            handler.sendMessage(message);
                        }catch (Exception e)
                        {
                            Toast.makeText(ctx , "Server connect error \n  服务器通信出错 " , Toast.LENGTH_LONG).show();
                            bundle.putString("echo" , "Execption Occured");
                            message.setData(bundle);
                            handler.sendMessage(message);
                        }
                        Looper.loop();
                    }
                }
        ).start();


        while (!handlerEnd);



        return serverEcho.equals(SUCCESS);      */

        return true;
    }

    public static void SetNetAddr(byte[] Netaddr)
    {
        addr = Netaddr;
    }


    public static Boolean Login( String userName, String userPassword){

        return SendRequest(userName,userPassword,TYPE_LOGIN , "Test Device");
    }

    public static Boolean hasUser(String userName)
    {
        return SendRequest(userName,"DEFAULT",TYPE_CHECK,SystemUtil.getDeviceBrand());      //返回时SUCCESS代表用户存在
    }

    public static Boolean Register( String userName, String userPassword){
        return SendRequest(userName,userPassword,TYPE_REGISTER ,SystemUtil.getDeviceBrand());
    }

}